package com.viphome.servcice.impl;

import com.viphome.bean.Seckill;
import com.viphome.bean.SuccessKilled;
import com.viphome.bean.dto.Exposer;
import com.viphome.bean.dto.SeckillExecution;
import com.viphome.dao.RedisDao;
import com.viphome.dao.SeckillDao;
import com.viphome.dao.SuccessKilledDao;
import com.viphome.enums.SeckillStatEnum;
import com.viphome.exception.RepeatKillException;
import com.viphome.exception.SeckillCloseException;
import com.viphome.exception.SeckillException;
import com.viphome.mapper.DaoSuccessKilledMapper;
import com.viphome.servcice.SeckillService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangzhanjin on 2017/12/26.
 */
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private SeckillDao seckillDao;
    @Autowired
    private SuccessKilledDao successKilledDao;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private DaoSuccessKilledMapper daoSuccessKilledMapper;

    //md5盐值字符串，用于混淆MD5
    private final String slat = "beikbank88888888";

    public Seckill queryById(long seckillId) {
        return seckillDao.queryById(seckillId);
    }

    public List<Seckill> queryAll() {
        return seckillDao.queryAll(0, 0);
    }

    /**
     * 暴露接口，用redis，降低数据库压力
     * @param seckillId
     * @return
     */
    public Exposer exportSeckillUrl(long seckillId) {
        //优化点：缓存优化
        /**
         * get from cache
         * if null
         *  get db
         *  else
         *      put cache
         * login
         * 这个最好不要写在业务逻辑层里面，写在dao里，其它数据存储访问的包
         */
        //1.访问redis
        Seckill seckill = redisDao.getSeckill(seckillId);
        if(seckill ==null) {
            //2.访问数据库
            seckill = seckillDao.queryById(seckillId);
            if (seckill == null) {
                return new Exposer(false, seckillId);
            }else{
                //放入redis
                redisDao.putSeckill(seckill);
            }
        }

        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        Date nowTime = new Date();

        if (nowTime.getTime() < startTime.getTime() ||
                nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime());
        }
        //转化特定字符串过程，不可逆
        String md5 = getMD5(seckillId);//todo
        return new Exposer(true,md5,seckillId);
    }

    private String getMD5(long seckillId){
        String base = seckillId+"/"+slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }



    /**
     * 使用注解控制事务方法的优点：
     * 1.开发团队达成一致约定，明确标注事务方法变成风格
     * 2.保证事务方法的执行时间尽可能短（第一次操作数据库的时候，告诉数据库开启事务）
     * 不要穿插其它的网络操作，RPC/HTTP请求/太长了，或者剥离到事务方法外，比如再做一个更上层的方法
     * 3.不是所有的方法都需要事务，如果只有一条修改操作，只读操作不需要事务控制（mysql行级锁）
     * （基于数据库的秒杀）
     */
    @Transactional
    public SeckillExecution excuteSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {

        if(md5 == null||!md5.equals(getMD5(seckillId))){
            throw new SeckillException("seckill data rewrite");
        }
        //执行秒杀逻辑，减库存+记录购买行为
        Date nowTime = new Date();

        try {
            //记录购买行为
            int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
            //唯一：seckillId，userPhone
            if(insertCount<=0){
                //重复秒杀
                throw new RepeatKillException("seckill repeat");
            }else{
                //减库存，热点商品竞争
                int updateCount = seckillDao.redeuceNumber(seckillId,nowTime);
                if(updateCount<=0){
                    //没有更新到记录，秒杀结束，rollback
                    throw new SeckillCloseException("seckill is closed");
                }else{
                    //秒杀成功 commit
                    SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, successKilled);
                }

            }


        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepeatKillException e2) {
            throw e2;
        } catch (Exception e) {
            e.printStackTrace();
            //所有编译期异常，转化为运行期异常，SeckillException继承自RuntimeE
            //一旦有错，不管什么错，都回滚
            throw new SeckillException("seckill inner error：");
        }
    }

    public SeckillExecution excuteSeckillProcedure(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {

        if(md5 == null||!md5.equals(getMD5(seckillId))){
            return new SeckillExecution(seckillId,SeckillStatEnum.DATE_REWRITE);
        }
        Date killTime = new Date();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("seckillId", seckillId);
        map.put("phone", userPhone);
        map.put("killTime", killTime);
        map.put("result", null);
        //执行存储过程，result被赋值
        try {
            daoSuccessKilledMapper.killByProcedure(map);
            //获取result
            Integer result = MapUtils.getInteger(map, "result", -2);
            if(result==1){
                SuccessKilled sk = successKilledDao.queryByIdWithSeckill(seckillId,userPhone);
                return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS,sk);
            }else{
                return new SeckillExecution(seckillId, SeckillStatEnum.stateOf(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR);
        }
    }
}
